// @login and register
const express = require('express')
const bcrypt = require('bcryptjs')
const gravatar = require('gravatar')
const jwt = require('jsonwebtoken')
const passport = require('passport')

const {
  secretOrKey
} = require('../../config/keys')

const router = express.Router()

const User = require('../../models/User')

/**
 * @route GET /api/user/login
 * @desc 返回请求的json数据
 * @access private
 */
router.get('/login', passport.authenticate('jwt', {
  session: false
}), (req, res) => {
  res.json({
    id: req.user.id,
    name: req.user.name,
    email: req.user.email,
    identity: req.user.identity,
    avatar: req.user.avatar
  })
})

/**
 * @rotue post /api/user/login
 * @desc 返回token jwt passport
 * @access public
 */
router.post('/login', (req, res) => {
  const email = req.body.email
  const password = req.body.password
  User.findOne({
      email
    })
    .then(user => {
      if (!user) { // 如果用户不存在
        return res.status(404).json({
          email: '用户不存在，请注册'
        })
      }

      // 如果用户已经注册 验证密码是否正确
      bcrypt.compare(password, user.password)
        .then(isMatch => {
          if (isMatch) {
            const rule = { // 
              id: user.id,
              name: user.name,
              email: user.email,
              avatar: user.avatar,
              identity: user.identity
            }
            jwt.sign(rule, secretOrKey, {
              expiresIn: 3600 // 过期时间
            }, (err, token) => {
              if (err) {
                throw err
              }
              return res.json({
                success: true,
                token: 'Bearer ' + token
              })
            })
          } else {
            return res.status(400).json({
              message: '密码错误'
            })
          }
        })
    })
})


/**
 * @route POST /api/user/register
 * @desc 返回请求的json数据
 * @access public
 */
router.post('/register', (req, res) => {
  User.findOne({
      email: req.body.email
    })
    .then((user) => {
      if (user) {
        // 用户已存在
        return res.status(400).json({
          message: '邮箱已存在'
        })
      } else {
        const avatar = gravatar.url(req.body.email, {
          s: '200',
          r: 'pg',
          d: 'mm'
        })
        // 创建一个新用户
        const newUser = new User({
          name: req.body.name,
          email: req.body.email,
          avatar,
          password: req.body.password,
          identity: req.body.identity
        })
        // 使用bcrypt对密码进行加密处理
        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            // Store hash in your password DB.
            if (err) {
              throw err
            }
            // 给密码加密
            newUser.password = hash
            newUser.save()
              .then((user) => {
                res.json(user)
              })
              .catch((err) => {
                console.log(err)
              })
          })
        })
      }
    })
})

module.exports = router